package com.ss.lambda.demo1;

/**
 * @Auther: ljy.s
 * @Date: 2022/9/12 - 09 - 12 - 0:16
 */

/**
 * Lambda表达式初体验
 */
public class LambdaTest {
    public static void main(String[] args) {
        // 1.子类实现接口
        Factory factory = new SubClass(); // 多态
        User user1 = (User) factory.getObject();
        System.out.println(user1);

        // 2.匿名内部类
        factory = new Factory() {
            @Override
            public Object getObject() {
                return new User("张三", 38);
            }
        };
        User user2 = (User) factory.getObject();
        System.out.println(user2);

        // 3.Lambda表达式
        /*factory = () -> {
            return new User("李四", 32);
        };*/
        factory = () -> new User("李四", 32);
        User user3 = (User) factory.getObject();
        System.out.println(user3);

        // Lambda作为参数进行传递
        User user4 = getUserFromFactory(() -> {
            return new User("赵六", 33);
        }, "User");
        System.out.println(user4);

        // Lambda作为函数的返回值
        factory = getFactory();
        System.out.println(factory.getObject());
    }

    public static User getUserFromFactory(Factory factory, String beanName) {
        Object obj = factory.getObject();
        if (obj != null && obj.getClass().getSimpleName().equals(beanName)) {
            return (User) obj;
        }
        return null;
    }

    public static Factory getFactory() {
        return () -> {
            return new User("赵奔", 30);
        };
    }
}
